<template>
  <div class="layout-pd">
    <zh-space>
      <zh-card>
        <zh-form ref="wtTaskQueryForm" :model="state.queryParam">
          <zh-form-input
            prop="taskName"
            label="任务名称"
            placeholder="支持模糊查询"
            v-model="state.queryParam.taskName"
          ></zh-form-input>
          <zh-form-select
            prop="taskType"
            label="任务类型"
            placeholder="单选"
            :options="state.dictData.WTTASKTYPE"
            v-model="state.queryParam.taskType"
          ></zh-form-select>
          <template v-if="state.advanced">
            <zh-form-date prop="taskStartTime" label="任务开始日期" format="YYYY-MM-DD"
                          v-model="state.queryParam.taskStartTime"></zh-form-date>
            <zh-form-date prop="taskEndTime" label="任务结束日期" format="YYYY-MM-DD"
                          v-model="state.queryParam.taskEndTime"></zh-form-date>
          </template>
          <zh-col>
            <zh-button buttonType="add" @click="createWtTask">创建任务</zh-button>
            <zh-button buttonType="query" @click="queryBtn">
              查询
            </zh-button>
            <el-link type="primary" @click="toggleAdvanced" style="margin-left: 8px">
              {{ state.advanced ? '收起' : '展开' }}
              <el-icon v-if="state.advanced"><ele-ArrowUp /></el-icon>
              <el-icon v-else><ele-ArrowDown /></el-icon>
            </el-link>
          </zh-col>
        </zh-form>
      </zh-card>
      <div style="width: 100%">
        <el-tabs type="border-card" v-model="state.tabKey">
        <el-tab-pane label="我创建的" name="myCreate">
          <zh-table
              ref="myCreateWtTaskQueryTable"
              :height="jsHeight()"
              funcCode="wtTaskQuery005"
              :columns="state.myCreateTableColumn"
              :radio-config="{ trigger: 'row' }"
              :disabled="false"
          >
            <template #operate_default="{ row }">
              <zh-button link  button-type="query" @click="queryWtTask(row)">查询 </zh-button>
              <zh-button v-func:wtTask006  link  button-type="edit" @click="editWtTask(row)" v-if="row.editOperaFlag">编辑 </zh-button>
              <zh-button v-func:wtTask002 link icon="ele-Avatar" type="primary" @click="assignWtTask(row)" v-if="row.assignOperaFlag">分配 </zh-button>
              <zh-button v-func:wtTask007 link button-type="del" @click="revokeWtTask(row)" v-if="row.revokeTaskOperaFlag">撤销 </zh-button>
            </template>
          </zh-table>
        </el-tab-pane>
        <el-tab-pane label="分配给我的" name="assignForMe">
          <zh-table
              ref="assignForMeWtTaskQueryTable"
              :height="jsHeight()"
              funcCode="wtTaskQuery006"
              :columns="state.assignForMeTableColumn"
              :radio-config="{ trigger: 'row' }"
              :disabled="false"
          >
            <template #taskAllocaStatus="{ row }">
              <el-tag v-if="row.taskAllocaStatus !== null"
                      v-for="e in taskAllocaStatusFilter(row.taskAllocaStatus)"
                      :key="e.label"
                      :type="e.type"
                      effect="dark"
              >
                {{ e.label }}
              </el-tag>
              <span v-else>{{ row.taskAllocaStatusName }}</span>
            </template>

            <template #operate_default="{ row }">
              <zh-button link  button-type="query" @click="queryWtTask(row)">查询 </zh-button>
              <zh-button v-func:wtTask004 link icon="ele-EditPen" type="primary" @click="startWtTask(row)" v-if="row.startOperaFlag">开启 </zh-button>
              <zh-button v-func:wtTask005 link icon="ele-EditPen" type="primary" @click="completeWtTask(row)" v-if="row.completeOperaFlag">完成 </zh-button>
              <zh-button v-func:wtTask003 link button-type="add" @click="createChildWtTask(row)" v-if="row.createChildTaskOperaFlag">创建 </zh-button>
            </template>
          </zh-table>
        </el-tab-pane>
      </el-tabs>
      </div>
    </zh-space>

    <zh-dialog
        :title="state.modelTitle"
        width="30%"
        v-model="state.createWtTaskVisible"
        @confirm="handleCreateOrEditWtTask"
        @cancel="cancelCreateOrEditWtTask"
    >
      <formForCreateWtTask v-model="state.wtTaskVO"></formForCreateWtTask>
    </zh-dialog>

    <use-select
        v-if="state.selectVisible"
        ref="useselect"
        @closed="state.selectVisible = false"
        @handleSaveData="handleSaveData"
        ></use-select>

    <zh-dialog
        title="任务开启"
        width="30%"
        v-model="state.startWtTaskVisible"
    >
      <template v-slot:footer>
        <el-button @click="cancelStartWtTask"> 关闭 </el-button>
        <el-button type="primary" @click="handleStartWtTask"> 开启 </el-button>
      </template>
      <formForStartWtTask ref="startWtTaskForm"></formForStartWtTask>
    </zh-dialog>

    <zh-dialog
        title="去完成"
        width="50%"
        v-model="state.completeWtTaskVisible"
    >
      <template v-slot:footer>
        <el-button @click="cancelCompleteWtTask"> 关闭 </el-button>
        <el-button type="primary" @click="handleCompleteWtTask"> {{ state.completeWtTaskTitle }} </el-button>
      </template>
      <formForExecuteWtTask :taskRealProgressLabel="state.wtTaskVO.taskRealProgressLabel" ref="formForExecuteWtTaskPage"
      @update:taskRealProgressLabel="updateTaskRealProgressLabel"></formForExecuteWtTask>
    </zh-dialog>

    <wt-task-detail-drawer
        :visible="state.wtTaskDetailDrawer"
        @update:modelValue="drawerForClose"
        :taskId="state.wtTaskVO.taskId"
        :wtTaskAllocationId="state.wtTaskVO.wtTaskAllocationId"
        :createOrAssignPerson="state.wtTaskVO.createOrAssignPerson"
    ></wt-task-detail-drawer>
  </div>
</template>

<script lang="ts" setup name="wtTask">
import useSelect from '@/components/scWorkflow/select.vue'
import formForStartWtTask from './component/formForStartWtTask.vue'
import logTableForWtTask from './component/logTableForWtTask.vue'
import wtTaskDetailDrawer from './component/wtTaskDetailDrawer.vue'
import formForExecuteWtTask from './component/formForExecuteWtTask.vue'
import formForCreateWtTask from './component/formForCreateWtTask.vue'
import { defineAsyncComponent, ref, reactive, onMounted, nextTick, computed, watch } from 'vue';
import { useRoute} from 'vue-router';
//------------------定义子组件---------------------------
const assignForMeWtTaskQueryTable = ref<any>({});
const myCreateWtTaskQueryTable = ref<any>({});
const useselect = ref(null);
const startWtTaskForm = ref(null);
const formForExecuteWtTaskPage = ref(null);
const route = useRoute();

//------------------内部变量定义-------------------------
const state = reactive({
  tabKey: 'assignForMe',
  processDisabled: false,
  dictData: {} as any,
  // 高级搜索 展开/关闭
  advanced: false,
  // 查询参数
  queryParam: {} as any,
  modelTitle: undefined,
  // 表头
  loading: false,
  tablePage: {
    total: 0,
    currentPage: 1,
    pageNum: 1,
    pageSize: 20,
  },
  myCreateTableColumn: [
    { type: "seq", width: 80, fixed: "left", align: "center", title: "序号" },
    { field: "taskName", title: "任务名称", align: "center", fixed: "left", width: 180 },
    { field: "taskDesc",title: "任务描述",align: "center",fixed: "left",width: 200,},
    { field: "parentTaskName", title: "父级任务", align: "center", width: 180 },
    { field: "taskStartTime",title: "任务开始日期",align: "center",width: 120,},
    { field: "taskEndTime",title: "任务结束日期",align: "center",width: 120,},
    { field: "taskStatusName", title: "任务状态", align: "center", width: 80 },
    { field: "isAssignName", title: "是否分配人员", align: "center", width: 120 },
    { field: "fullNames", title: "分配人员", align: "center", width: 200 },
    { field: "unfinishedPersons", title: "未完成人员", align: "center", width: 200 },
    { field: "taskLabel", title: "任务标签", align: "center" , width: 80},
    { field: "predictWorkHours", title: "预估工时", align: "center", width: 80},
    { field: "taskRealProgressLabel", title: "任务最终进度", align: "center", width: 120},
    { field: "completedTime", title: "完成时间", align: "center", width: 200},
    { field: "createFullName", title: "创建人", align: "center", width: 100 },
    { field: "orgName", title: "创建人所属组织", align: "center", width: 150 },
    { field: "createTime", title: "创建时间", align: "center", width: 200 },
    { field: "remarks", title: "备注", align: "center", width: 120 },
    { field: 'operate', title: '操作', align: 'center', fixed: 'right', width: 250, slots: { default: 'operate_default' } },
  ],
  assignForMeTableColumn: [
    { type: "seq", width: 80, fixed: "left", align: "center", title: "序号" },
    { field: "taskName", title: "任务名称", align: "center", fixed: "left", width: 180 },
    { field: "taskDesc",title: "任务描述",align: "center",fixed: "left",width: 200,},
    { field: "parentTaskName", title: "父级任务", align: "center", width: 180 },
    { field: "taskStartTime",title: "任务开始日期",align: "center",width: 120,},
    { field: "taskEndTime",title: "任务结束日期",align: "center",width: 120,},
    { field: "taskAllocaStatusName", title: $store.user.userInfo?.fullName+"任务执行情况", align: "center", width: 180,
      editRender: {},
      slots: {
        // 使用插槽模板渲染
        default: "taskAllocaStatus",
      },},
    { field: "taskLabel", title: "任务标签", align: "center" , width: 80},
    { field: "predictWorkHours", title: "预估工时", align: "center", width: 80},
    { field: "taskRealProgressLabel", title: "任务最终进度", align: "center", width: 120},
    { field: "completedTime", title: "完成时间", align: "center", width: 200},
    { field: "createFullName", title: "创建人", align: "center", width: 100 },
    { field: "orgName", title: "创建人所属组织", align: "center", width: 150 },
    { field: "createTime", title: "创建时间", align: "center", width: 200 },
    { field: "remarks", title: "备注", align: "center", width: 120 },
    { field: 'operate', title: '操作', align: 'center', fixed: 'right', width: 280, slots: { default: 'operate_default' } },
  ],
  tableData: [],
  createWtTaskVisible: false,
  wtTaskVO: {
    taskName: "",
    taskDesc: "",
    taskType: undefined,
    taskStartTime: undefined,
    taskEndTime: undefined,
    taskLabel: undefined,
    predictWorkHours: undefined,
    remarks: undefined,
    taskWorkRatioLabel: undefined,
    createWtTaskForChild: false,
  },
  selectVisible: false,
  startWtTaskVisible: false,
  completeWtTaskVisible: false,
  selectParentTaskId: undefined,
  wtTaskDetailDrawer: false,
  completeWtTaskTitle: undefined
});

const taskAllocaStatusList = ref<Array<Item>>([
  {type: "info", label: "未开始", value: 0},
  {type: "primary", label: "进行中", value: 1},
  {type: "success", label: "已完成", value: 2},
]);

//------------------定义调用方法-------------------------
const taskAllocaStatusFilter = (taskAllocaStatus) => {
  return taskAllocaStatusList.value.filter((item) => item.value == taskAllocaStatus);
};

function jsHeight() {
  return document.documentElement.clientHeight - 290;
}

function toggleAdvanced() {
  state.advanced = !state.advanced;
}

function queryBtn() {
  findWtTaskList();
}

function drawerForClose(val) {
  state.wtTaskDetailDrawer = val;
  if(val === false){
    findWtTaskList();
  }
}

function resetWtTaskVO() {
  state.wtTaskVO = {
    taskName: "",
    taskDesc: "",
    taskType: undefined,
    taskStartTime: undefined,
    taskEndTime: undefined,
    taskLabel: undefined,
    predictWorkHours: undefined,
    remarks: undefined,
    taskWorkRatioLabel: undefined,
    createWtTaskForChild: false,
  };
  state.selectParentTaskId = undefined;
}
function queryWtTask(row) {
  state.wtTaskVO = row;
  state.wtTaskDetailDrawer = true;
}
function createWtTask() {
  resetWtTaskVO();
  state.modelTitle = '创建任务';
  state.createWtTaskVisible = true;
}
function cancelCreateOrEditWtTask() {
  state.createWtTaskVisible = false;
  resetWtTaskVO();
}
function handleCreateOrEditWtTask() {
  if(state.wtTaskVO.createWtTaskForChild){
    const params = {parentId: state.selectParentTaskId};
    Object.assign(params,state.wtTaskVO)
    $api.common.send
        .post("wtTask003", params)
        .then(() => {
          $messageBox.success("子任务创建成功", "提示");
          refreshList();
          cancelCreateOrEditWtTask();
        })
        .catch(() => {});
    return;
  }
  if(state.modelTitle === '创建任务'){
    $api.common.send
        .post("wtTask001", state.wtTaskVO)
        .then(() => {
          $messageBox.success("任务创建成功", "提示");
          refreshList();
          cancelCreateOrEditWtTask();
        })
        .catch(() => {});
  }else if(state.modelTitle === '编辑任务'){
    $api.common.send
        .post("wtTask006", state.wtTaskVO)
        .then(() => {
          $messageBox.success("任务编辑成功", "提示");
          refreshList();
          cancelCreateOrEditWtTask();
        })
        .catch(() => {});
  }
}
function findWtTaskList() {
  if(state.tabKey === 'myCreate'){
    myCreateWtTaskQueryTable.value.query(state.queryParam);
  }else if(state.tabKey === 'assignForMe'){
    assignForMeWtTaskQueryTable.value.query(state.queryParam);
  }
}
function refreshList() {
  if(state.tabKey === 'myCreate'){
    myCreateWtTaskQueryTable.value.refresh(state.queryParam);
  }else if(state.tabKey === 'assignForMe'){
    assignForMeWtTaskQueryTable.value.refresh(state.queryParam);
  }
}

function editWtTask(row) {
  state.modelTitle = '编辑任务';
  state.wtTaskVO = row;
  state.createWtTaskVisible = true;
}

//分配任务给指定用户，用户可以多个，也可以没有，进入任务池中
function assignWtTask(row) {
  state.wtTaskVO = row;
  state.selectVisible = true;
  nextTick(() => {
    useselect.value.open(1, row.assignerList? row.assignerList:[],{showOrg: true,groupFrom: "org",hasOnlyOne: false});
  });
}

function handleSaveData(data) {
  console.log(data)
  let userIdList = [];
  if(data && data.length > 0){
    data.forEach(item => {
      userIdList.push(item.id);
    })
  }
  $api.common.send
      .post("wtTask002", {taskId: state.wtTaskVO.taskId,userIdList: userIdList})
      .then(() => {
        $messageBox.success("任务分配成功", "提示");
        refreshList();
        resetWtTaskVO();
      })
      .catch(() => {});
}

//开启任务-弹出框
function startWtTask(row) {
  state.wtTaskVO = row;
  state.startWtTaskVisible = true;
}

function cancelStartWtTask() {
  state.startWtTaskVisible = false;
  resetWtTaskVO();
}

//处理开启任务
function handleStartWtTask() {
  const params = {taskId: state.wtTaskVO.taskId};
  Object.assign(params,startWtTaskForm.value?.getData());
  $api.common.send
      .post("wtTask004", params)
      .then(() => {
        $messageBox.success("任务开启成功", "提示");
        refreshList();
        cancelStartWtTask()
      })
      .catch(() => {});
}

//完成任务
function completeWtTask(row) {
  state.wtTaskVO = row;
  state.completeWtTaskVisible = true;
}

function cancelCompleteWtTask() {
  state.completeWtTaskVisible = false;
  resetWtTaskVO();
}

function updateTaskRealProgressLabel(val) {
  if(val === '100%'){
    state.completeWtTaskTitle = '完成';
  }else {
    state.completeWtTaskTitle = '修改进度';
  }
}

function handleCompleteWtTask() {
  const params = {taskId: state.wtTaskVO.taskId};
  Object.assign(params,formForExecuteWtTaskPage.value.getData())
  $api.common.send
      .post("wtTask005", params)
      .then(() => {
        $messageBox.success("任务完成成功", "提示");
        refreshList();
        cancelCompleteWtTask()
      })
      .catch(() => {});
}

//创建子级任务
function createChildWtTask(row) {
  state.wtTaskVO = {};
  state.wtTaskVO.createWtTaskForChild = true;
  state.selectParentTaskId = row.taskId;
  state.modelTitle = '创建子任务';
  state.createWtTaskVisible = true;
}

//撤销任务
function revokeWtTask(row) {
  $api.common.send
      .post("wtTask007", {taskId: row.taskId})
      .then(() => {
        $messageBox.success("任务撤销成功", "提示");
        refreshList();
        cancelCompleteWtTask()
      })
      .catch(() => {});
}

//------------------初始化------------------------------

// 数据字典初始化
const initDict = () => {
  const params = {
    dictFields: "WTTASKTYPE",
  };
  $api.common.getBatchDict.post(params).then((res) => {
    state.dictData = res.result;
  });
  console.log(route.query.taskId)
};

onMounted(() => {
  nextTick(() => {
    initDict();
    findWtTaskList();
  });
});

watch(
    () => route,
    () => {
      console.log(route)
    },
    {
      deep: true,
    }
);

watch(
    () => state.tabKey,
    () => {
      findWtTaskList();
    },
    {
      deep: true,
    }
);
</script>
<style lang="scss" scoped>
:deep(.el-dialog__body) {
  overflow-x: auto !important;
}
</style>
